// pages/head-foot/head-foot.js
"use strict";
let hyMath = require('../../utils/math.js');
var utils = require('../../utils/utils.js');
var modal = require('../../utils/modal.js');

var storage = require('../../utils/storage.js')
var request = require('../../utils/request.js')
var auth = require('../../utils/auth.js');
var config = require('../../config.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        clickSubmit: false,
        id: '',
        num: '',
        points: '',
        fmtDate:'',
        date:'',



        vehicleImg: '',

        urlP: {
            items: undefined,
            discounts: undefined
        },
        userInfo: {
            real_name: '',
            head_img_url: '',
            default_img_url: '../../images/ic-touxiang-moren.png',
        },
        // hasLogin: true,
        // headImg: '../../images/head.png',
        right: '../../images/right.png',
        // border: '../../images/news-choose.png',
        // name: '新于',
        // car: '京A88888',
        // cart: '钻石用户1折',
        navItems: [
            {
                name: '保养',
                checked: true
            },
            {
                name: '装饰',
                checked: false
            },
            {
                name: '储值',
                checked: false
            }
        ],
        submitEx: {
            "member_id": "", // 会员id（新、旧会员id，两者只能有一个存在）
            "old_member_id": "", // 旧会员id（新、旧会员id，两者只能有一个存在）
            "license_number": "", // 车牌号
            "work_sheet_type":
                1, // 开单类型 1=保养；2=装饰；3=储值
        },
        submitP: {
            1: {
                "total_amount":
                    '', // 结算总额
                "amount":
                    '', // 实付总金额
                "work_cost":
                    '', // 工时费用
                "parts_cost":
                    '', // 零件费用
                "additional_cost":
                    '', // 附加费用
                "total_discount":
                    '',// 优惠总额
                "syn_discount":
                    '', // 综合优惠
                "work_discount":
                    '', //工时优惠
                "other_discount":
                    '', // 其他优惠
                "add_bonus":
                    '' // 新增积分
            }
            ,
            2: {
                "total_amount":
                    '', // 结算总额
                "amount":
                    '', // 实付总金额
                "total_discount":
                    '',// 优惠总额
                "add_bonus":
                    '' // 新增积分
            }
            ,
            3: {
                "total_amount":
                    '', // 结算总额
                "amount":
                    '', // 实付总金额
                "total_discount":
                    '',// 优惠总额
                "add_bonus":
                    '' // 新增积分
            }
        }
        // money: '700.00',
        // hasMoney: true,
        // totalNum: '0.00',   //总额
        // reduce: '',     //优惠金额
        // points: '',      //积分
        // save: '¥1000.00',  //储值金额
        // send: '¥300.00'    //赠送金额
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        let urlP = that.data.urlP;
        let oldO = {};
        let newO = {};
        let items = urlP.items;
        let userInfo = that.data.userInfo;
        let submitP = that.data.submitP;
        let submitEx = that.data.submitEx;

        that.setData({
            clickSubmit: false
        })

        if (typeof urlP.items != 'undefined') {
            oldO = {
                real_name: items.real_name,
                head_img_url: items.head_img_url,
                car: items.cars && items.cars[0] && items.cars[0].license_number,
                level: items.level
            }
            Object.assign(newO, userInfo, oldO)
            that.setData({
                userInfo: newO
            });
            // 修改扩展对象
            submitEx.member_id = items.member_id
            submitEx.old_member_id = items.old_member_id
            submitEx.license_number = items.cars && items.cars[0] && items.cars[0].license_number
            that.setData({
                submitEx: submitEx
            });
            if (items.cars == '') {
                wx.showToast({
                    title: '此用户没有车牌信息',
                    icon: 'success',
                    duration: 2000
                })
            }

            that.setData({
                'urlP.items': undefined
            });
        }

        if (typeof urlP.discounts != 'undefined') {
            let discounts = urlP.discounts;
            // Object.assign(newO, userInfo ,oldO)
            let total_discount = discounts.total_discount;
            let syn_discount = discounts.syn_discount;
            let work_discount = discounts.work_discount;
            let other_discount = discounts.other_discount;
            submitP['1'].total_discount = total_discount;
            submitP['1'].syn_discount = syn_discount;
            submitP['1'].work_discount = work_discount;
            submitP['1'].other_discount = other_discount;
            that.setData({
                submitP: submitP
            });

            that.setData({
                'urlP.discounts': undefined
            });
            that.watchAutoChage();
        }
    },

    uploadVehicleImgCallback(e) {
        var vehicleImg = e.detail && (e.detail.data.image_url || '');
        //有服务的时候
        var that = this;
        let data = that.data;
        let submitP1 = data.submitP['1'];

        var dataP = {
            "img_url": vehicleImg, // 上传发票的地址 url
            "img_type": "3" // 发票类型：2
        }
        modal.loading()

        request.post({path: config.analysis}, dataP).then(res => {
            modal.hide()
            if (res.data.ret == 0) {
                let data = res.data.data.data;
                let additional_cost = data.additional_cost;
                let work_cost = data.work_cost;
                let parts_cost = data.parts_cost;
                let total_amount = data.total_amount;
                submitP1.additional_cost = additional_cost;
                submitP1.work_cost = work_cost;
                submitP1.parts_cost = parts_cost;
                submitP1.total_amount = total_amount;
                that.setData({
                    'submitP.1':submitP1
                })
                that.watchAutoChage();
            }
            modal.toast(res.data.msg)
        })
    },

    /**
     * 点击选择优惠
     */
    tapLinkDiscounts: function () {
        let that = this;
        let discounts = that.data.submitP['1'];
        // Object.assign(newO, userInfo ,oldO)
        let total_discount = discounts.total_discount || '';
        let syn_discount = discounts.syn_discount || '';
        let work_discount = discounts.work_discount || '';
        let other_discount = discounts.other_discount || '';

        let work_cost = discounts.work_cost;
        let parts_cost = discounts.parts_cost;
        let additional_cost = discounts.additional_cost;
        let member_id = that.data.submitEx.member_id;
        if(!member_id){
            wx.showToast({
                icon: 'none',
                title: '请选择用户'
            })
            return false;
        }else{
            wx.navigateTo({
                // url: '../../pages/can-use/can-us?total_discount=$total_discount&syn_discount=$syn_discount&work_discount=$work_discount&other_discount=$other_discount'
                url: '../../pages/can-use/can-use?total_discount=' + total_discount + '&syn_discount=' + syn_discount + '&work_discount=' + work_discount + '&other_discount=' + other_discount
                + '&work_cost='+work_cost+'&parts_cost='+parts_cost+  '&additional_cost='+additional_cost+'&member_id='+member_id
            })
        }

    },

    /**
     * 选项卡函数，且改变数据类型；
     * @param e
     */
    checked: function (e) {
        let that = this;
        var index = e.target.dataset.index;
        // 标题
        var navItems = this.data.navItems
        // 取消所有title的选中
        for (var i = 0; i < navItems.length; i++) {
            navItems[i]['checked'] = false
        }
        ;
        // 选中当前title
        navItems[index]['checked'] = true

        that.data.submitEx.work_sheet_type = parseInt(index + 1);

        // 改变类型值
        that.setData({
            submitEx: that.data.submitEx
        })

        this.setData({
            navItems: navItems
        })

    },
    /**
     * 确定提交
     */
    clickSubmit: function (e) {
        let that = this;
        if(that.data.clickSubmit){
            return false;
        }

        //类型，扩展对象，新对象
        let ex = that.data.submitEx;
        let type = ex.work_sheet_type;
        let submitP = that.data.submitP[type];

        if (!that.data.submitEx.member_id && !that.data.submitEx.old_member_id) {
            wx.showToast({
                icon: 'none',
                title: '请选择用户'
            })
            return false;
        }

        let title = '总额不能为0'
        if (!submitP.total_amount) {
            if (type == 3) {
                title = '储值金额不能为0'
            } else {

            }
            wx.showToast({
                title: title,
                icon: 'success',
                duration: 2000
            })
            return false
        }

        //新对象
        let data = {};
        Object.assign(data, submitP, ex);

        that.setData({
            clickSubmit: true
        })


        that.submitAjax(data);
    },
    // 提交请求
    submitAjax: function (data) {
        let that = this;
        console.log(data)
        request.post({'path': config.worksheet}, data).then(function (res) {
            var ratingData = res.data;
            if (ratingData.ret) {
                wx.showToast({
                    icon: 'none',
                    title: res.data.msg
                })
                return false;
            }
            that.setData({
                clickSubmit: false
            })
            wx.navigateTo({
                url: '/pages/work-center/work-center?type=1',
            })
            // console.log(ratingData)
            // that.setData({
            //
            // });

        }, function (res) {
            that.setData({
                clickSubmit: false
            })
            wx.showToast({
                icon: 'none',
                title: res.data.msg
            })
            return false;
        })
    },
    /**
     * input 响应模版数据到js中；
     * @param e
     * bindinput="inputKey"  data-name="submitP.2.total_discount" value="{{submitP['2'].total_discount}}"
     */
    inputKey: function (e) {
        let that = this;
        let lsData = that.data;
        let name = e.currentTarget.dataset.name;
        let nameArr = name.split(".");
        let newVal = e.detail.value;
        let nameArrLen = nameArr.length
        for (let i = 0; i <= nameArrLen; i++) {
            let val = lsData[nameArr[i]];
            if (nameArrLen - 1 === i) {
                lsData[nameArr[i]] = newVal;
            } else {
                lsData = lsData[nameArr[i]];
            }
        }
        this.setData({
            submitP: that.data.submitP
        })
        that.watchAutoChage()
        // debugger
    },
    //监听数据变化响应
    watchAutoChage: function () {
        let that = this;
        let data = that.data;
        let submitP = data.submitP;
        let submitEx = data.submitEx;
        let submitP1 = submitP[1];
        let submitP2 = submitP[2];
        let submitP3 = submitP[3];

        if (submitEx.work_sheet_type == 1) {

            submitP1.work_discount = hyMath.hyTofloat2(submitP1.work_discount);
            submitP1.syn_discount = hyMath.hyTofloat2(submitP1.syn_discount);
            submitP1.amount = hyMath.hyTofloat2(submitP1.amount);
            submitP1.total_discount = hyMath.hyTofloat2(submitP1.total_discount);
            submitP1.total_amount = hyMath.hyTofloat2(submitP1.total_amount);
            submitP1.other_discount = hyMath.hyTofloat2(submitP1.other_discount);

            submitP1.work_cost = hyMath.hyTofloat2(submitP1.work_cost);
            submitP1.parts_cost = hyMath.hyTofloat2(submitP1.parts_cost);
            submitP1.additional_cost = hyMath.hyTofloat2(submitP1.additional_cost);
            /**
             * 保养；
             */
            //总额
            submitP1.total_amount = hyMath.hyadd(submitP1.work_cost, submitP1.parts_cost, submitP1.additional_cost);

            //优惠总额  = 其他优惠想加
            submitP1.total_discount = hyMath.hyadd(submitP1.work_discount, submitP1.syn_discount, submitP1.other_discount);

            //实付总金额  = 总额 - 优惠额
            submitP1.amount = hyMath.hyjian(submitP1.total_amount, submitP1.total_discount);

            submitP1.amount = submitP1.amount > 0 ? submitP1.amount : 0;
            //新增积分 = 总额1比1；
            submitP1.add_bonus = hyMath.hyTofloat0(submitP1.amount);

            submitP1.amount = hyMath.hyTofloat2(submitP1.amount);

            submitP1.total_amount = hyMath.hyTofloat2(submitP1.total_amount);


        }

        if (submitEx.work_sheet_type == 2) {
            /**
             * 装饰
             */
            submitP2.total_amount = hyMath.hyTofloat2(submitP2.total_amount);
            submitP2.total_discount = hyMath.hyTofloat2(submitP2.total_discount);
            submitP2.amount = hyMath.hyTofloat2(submitP2.amount);
            submitP2.add_bonus = hyMath.hyTofloat2(submitP2.add_bonus);

            if(submitP2.total_discount > submitP2.total_amount){
                submitP2.total_discount = submitP2.total_amount;
            }


            //实付总金额  = 总额 - 优惠额
            submitP2.amount = hyMath.hyTofloat2(hyMath.hyjian(submitP2.total_amount, submitP2.total_discount));
            submitP2.amount = submitP2.amount > 0 ? submitP2.amount : 0;

            //新增积分 = 总额1比1；
            submitP2.add_bonus = hyMath.hyTofloat0(submitP2.amount);
        }

        if (submitEx.work_sheet_type == 3) {
            /**
             * 储值
             */

            submitP3.amount = hyMath.hyTofloat2(submitP3.amount);
            submitP3.total_amount = hyMath.hyTofloat2(submitP3.total_amount);
            submitP3.total_discount = hyMath.hyTofloat2(submitP3.total_discount);
            submitP3.add_bonus = hyMath.hyTofloat2(submitP3.add_bonus);


            //实付总金额  = 总额 - 优惠额
            submitP3.amount = hyMath.hyTofloat2(hyMath.hyjian(submitP3.total_amount, submitP3.total_discount));
            submitP3.amount = submitP3.amount > 0 ? submitP3.amount : 0;

            //新增积分 = 总额1比1；
            submitP3.add_bonus = hyMath.hyTofloat0(submitP3.amount);
        }
        this.setData({
            submitP: submitP
        })
    }
})